package last.fm;

import java.io.IOException;
import java.io.InputStream;

import baseStructure.Log;

/***
 * @author Ragnvald Fuglestein
 */

@SuppressWarnings("unused")
public abstract class LastFmJob implements Runnable {
	private final Object callback;
	private final String user;
	protected String method;
	protected String[] params;
	protected InputStream result = null;
	
	public LastFmJob(final String user, final String[] params, Object callback) {
		this.user = user;
		this.params = params;
		this.callback = callback;
		LastFmJobWorker.addJob(this);
	}
	
	private void jobCompleted() {
		Log.d("lastfm." + method + " : Success!");
		LastFmJobWorker.jobCompleted(this);
	}
	
	private void jobFailed() { //TODO
		Log.e("lastfm." + method + " : Failed!");
		LastFmJobWorker.jobCompleted(this);
	}
	
	@Override public void run() {
		prepareRequest();
		try {
			result = LastFm.getInstance().request(method,params);
		} catch (IOException e) {
			e.printStackTrace();
			jobFailed();
		}
		
		boolean ret = processResult();

		if(ret) {
			jobCompleted();
		} else {
			jobFailed();
			return;
		}
		
		callback();
	}
	
	abstract protected void prepareRequest();
	abstract protected boolean processResult();
	abstract protected void callback();
}
